/* -----------------------------------------------------------------------------
 * PROJECT    : net.lwf
 * FILE       : PdfProcessingServlet.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * Dec 9, 2010  mycodetalks			       Created
 */
package net.lwf.web.servlet.pdf;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lwf.common.constant.ICommonConstant;
import net.lwf.constant.IDalConstant;
import net.lwf.entity.WebUser;
import net.lwf.exception.ExceptionUtil;
import net.lwf.factory.lookup.LookupFactory;
import net.lwf.file.util.FileReader;
import net.lwf.security.DesEncryptor;
import net.lwf.service.LookupService;
import net.lwf.util.web.WebUtil;
import net.lwf.web.constant.IWebConstant;

import lwf.db.manager.worksheet.WorkSheetManager;

/**
 * Class description goes here
 */
public class PdfProcessingServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public void init(ServletConfig servletconfig) throws ServletException {
		super.init(servletconfig);
	}
	   
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


    public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    	
    	String[] baseInfo = this.getPrintFile(request);
    	String wsId = baseInfo[0];
    	String filepath = baseInfo[1];
    	//String baseFolder = LookupFactory.getInstance().getValue(IDalConstant.PDF, IDalConstant.PDF_BASE_FOLDER_KEY);
    	String baseFolder = new LookupService().getValue(IDalConstant.PDF, IDalConstant.PDF_BASE_FOLDER_KEY);
    	
    	long id = Long.parseLong(wsId);
    	WebUser webuser = (WebUser) WebUtil.getAttribute(request, IWebConstant.WEB_USER);

		//Verify whether the file is printed/accessed by the logged in user in the current day
		WorkSheetManager manager = new WorkSheetManager();
		boolean wsaccessed = manager.workSheetAccessed(webuser.getUser().getId(), this.formatWsAccessKey(filepath));
		
		if(!wsaccessed || (wsaccessed && !manager.workSheetHasRestrictions(id))) {
		    String contentType = getServletContext().getMimeType(filepath);
	    	response.setContentType(contentType);
	        OutputStream out = response.getOutputStream();
	        byte[] pdfContent = FileReader.loadFile(baseFolder + filepath);
	        out.write(pdfContent, 0, pdfContent.length); //This should be same as out.write(b);
	        if (out != null) {
	            out.close();
	        }
	        //Log the entry
	        manager.logWorkSheetAccess(webuser.getUser().getId(), id, this.formatWsAccessKey(filepath));
		}
		else {
			//return mapping.findForward("printerror");
		}
	}
    
    private String[] getPrintFile(HttpServletRequest request) {
    	String[] data = new String[2];  //first element is wsId and second element is filepath
		String printKey = request.getParameter("key");

		if(printKey != null) {
			//decode the key first
			String decodedPrintKey = null;
			try {
				decodedPrintKey = URLDecoder.decode(printKey, ICommonConstant.CHARACTER_ENCODING);
			} catch (UnsupportedEncodingException useex) {
				ExceptionUtil.logAndThrowException(PdfProcessingServlet.class, useex);
			}
			decodedPrintKey = decodedPrintKey.replace(ICommonConstant.SPACE, ICommonConstant.PLUS);
			//decrypt key
			//String encryptionKey = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
			//String encryptionScheme = LookupFactory.getInstance().getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
			LookupService service = new LookupService();
			String encryptionKey = service.getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_KEY);
			String encryptionScheme = service.getValue(IDalConstant.SECURITY, IDalConstant.DESEDE_ENCRYPTION_SCHEME_KEY);
			
			DesEncryptor encryptor = new DesEncryptor(encryptionScheme, encryptionKey);
			String decrypted = encryptor.decrypt(decodedPrintKey);
			StringTokenizer stk = new StringTokenizer(decrypted, ICommonConstant.PIPE);
			String wsId = stk.nextToken();
			String filepath = stk.nextToken();

			data[0] = wsId;
			data[1] = filepath;

		}
		else {
			//No print key
		}
		return data;
    }
		
		private String formatWsAccessKey(String source) {
			String formatted = "";
			formatted = new StringBuilder(source).reverse().toString();
			int pos = formatted.indexOf(ICommonConstant.FORWARD_SLASH);
			formatted = formatted.substring(pos+1);
			formatted =  new StringBuilder(formatted).reverse().toString();
			return formatted;
		}

} //PdfProcessingServlet



